var express = require('express');
var router = express.Router();
const { Setting } = require('../../models');

const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

// 查询系统设置详情
router.get('/', async function (req, res, next) {
    try {
        const setting = await getSetting();
        success(
            res,
            '查询系统设置成功',
            {setting}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 更新系统设置
router.put('/', async function (req, res, next) {
    try {
        const setting = await getSetting();
        const body = filterBody(req.body);
        console.log('更新系统设置-->',body)
        await setting.update(body)
        success(
            res,
            '更新系统设置成功', {
                setting
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 icp
const filterBody = (body)=>{
    return {
        name: body.name,
        icp: body.icp,
        copyright: body.copyright
    }
}


/**
 * 查询当前系统设置
 * @param {*} req 
 */
async function getSetting() {
    const setting = await Setting.findOne();
    if (!setting) {
        throw new NotFoundError(`初始系统设置未找到，请运行种子文件`)
    }
    return setting;
}

module.exports = router;
